﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint;
using System.Web;
using System.Web.UI.WebControls.WebParts;

namespace Evolution.UI.WebParts
{
    [Serializable]
    public class PageActionAssertion : BaseAssertion
    {
        #region Properties

        public override string Caption
        {
            get { return "Page Action Web Part"; }
        }

        public PageActionOperator Operator { get; set; }

        public string WebPartID { get; set; }

        #endregion

        #region Methods

        public override void CreateInterface(ControlCollectionBuilder builder, PageActionEditor editor, int index)
        {
            // Key
            DropDownList paList = new DropDownList();
            paList.ID = "PAList" + index;
            paList.Style[HtmlTextWriterStyle.Width] = "175px";
            paList.ToolTip = "Select a Page Action Web Part";

            PageActionWebPart parent = editor.PageActionWebPart;
            SPWebPartManager manager = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(editor.Page);
            if (manager == null)
                throw new InvalidOperationException("The SPWebPartManager returned from GetCurrentWebPartManager method is null.");

            foreach (System.Web.UI.WebControls.WebParts.WebPart part in manager.WebParts)
                if (part as PageActionWebPart != null && part.ID != parent.ID)
                    paList.Items.Add(new ListItem(part.Title, part.ID));

            builder.AddControl(paList);

            builder.AddStaticText("&nbsp;");

            ImageButton image = new ImageButton();
            image.ID = "PARefresh" + index;
            image.BorderStyle = BorderStyle.None;
            image.Width = Unit.Pixel(14);
            image.Height = Unit.Pixel(13);
            image.ImageUrl = "/_layouts/images/Evolution/refresh.gif";
            image.AlternateText = "Refresh Web Part list";
            image.Click += new ImageClickEventHandler(this.ListRefresh);

            builder.AddControl(image);

            builder.AddErrorPlaceholder("PAList" + index);

            builder.AddStaticText("<br/><br/>");

            DropDownList list2 = new DropDownList();
            list2.ID = "PAAction" + index;
            list2.Items.Add(new ListItem("executes action", PageActionOperator.ExecutesAction.ToString()));
            list2.Items.Add(new ListItem("does not execute action", PageActionOperator.DoesNotExecuteAction.ToString()));
            list2.Style[HtmlTextWriterStyle.Width] = "175px";

            builder.AddControl(list2);
        }

        public override bool IsValidAssertion(PageActionWebPart part, out string errorMessage)
        {
            errorMessage = String.Empty;

            SPLimitedWebPartManager manager = SPContext.Current.Web.GetLimitedWebPartManager(HttpContext.Current.Request.Path, PersonalizationScope.Shared);
            if (manager == null)
                throw new InvalidOperationException("The SPLimitedWebPartManager returned from GetLimitedWebPartManager method is null.");

            PageActionWebPart pa = manager.WebParts[this.WebPartID] as PageActionWebPart;
            if (part == null)
                errorMessage = "The specified Web Part does not belong the collection of Web Parts on this page.";

            return String.IsNullOrEmpty(errorMessage);
        }

        public override string GetDescription()
        {
            SPLimitedWebPartManager manager = SPContext.Current.Web.GetLimitedWebPartManager(HttpContext.Current.Request.Path, PersonalizationScope.Shared);
            if (manager == null)
                throw new InvalidOperationException("The SPLimitedWebPartManager returned from GetLimitedWebPartManager method is null.");

            PageActionWebPart part = manager.WebParts[this.WebPartID] as PageActionWebPart;
            if (part == null)
                throw new InvalidOperationException(String.Format("The specified Web Part does not belong the collection of Web Parts on this page. Web Part ID = '{0}'.", this.WebPartID));

            return String.Format("Page Action Web Part '{0}' {1}", part.DisplayTitle, this.Operator == PageActionOperator.ExecutesAction ? " executes action " : " does not execute action ");
        }

        public override void SyncChanges(PageActionEditor editor, int index)
        {
            (editor.FindControl("PAList" + index) as DropDownList).SelectedValue = this.WebPartID;
            (editor.FindControl("PAAction" + index) as DropDownList).SelectedValue = this.Operator.ToString();
        }

        public override void ApplyChanges(PageActionEditor editor, int index)
        {
            DropDownList list = editor.FindControl("PAList" + index) as DropDownList;

            if (list.Items.Count == 0)
                editor.RaiseError("PAList" + index, "There are no other Page Action Web Parts in the page. Add a new Page Action Web Part before choosing this assertion.");

            this.WebPartID = list.SelectedValue;
            this.Operator = (PageActionOperator)Enum.Parse(typeof(PageActionOperator), (editor.FindControl("PAAction" + index) as DropDownList).SelectedValue);
        }

        public override bool Evaluate(Page page, PageActionWebPart part)
        {
            SPWebPartManager manager = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(page);
            if (manager == null)
                throw new InvalidOperationException("The SPWebPartManager returned from GetCurrentWebPartManager method is null.");

            PageActionWebPart pawp = manager.WebParts[this.WebPartID] as PageActionWebPart;
            if (pawp == null)
                throw new InvalidOperationException(String.Format("The specified Web Part does not belong the collection of Web Parts on this page. Web Part ID = '{0}'.", this.WebPartID));

            bool conditionEvaluation = Condition.Evaluate(pawp.Condition, page, part);

            return this.Operator == PageActionOperator.ExecutesAction && conditionEvaluation || this.Operator == PageActionOperator.DoesNotExecuteAction && !conditionEvaluation;            
        }

        public void ListRefresh(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;

            string index = button.ID.Substring(9);

            DropDownList paList = button.Parent.FindControl("PAList" + index) as DropDownList;
            if (paList != null)
            {
                paList.Items.Clear();

                PageActionWebPart parent = ((PageActionEditor)button.Parent.Parent).PageActionWebPart;
                SPWebPartManager manager = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(button.Page);
                if (manager == null)
                    throw new InvalidOperationException("The SPWebPartManager returned from GetCurrentWebPartManager method is null.");

                foreach (System.Web.UI.WebControls.WebParts.WebPart part in manager.WebParts)
                    if (part as PageActionWebPart != null && part.ID != parent.ID)
                        paList.Items.Add(new ListItem(part.Title, part.ID));
            }
        }

        #endregion
    }

    #region PageActionOperator enum

    public enum PageActionOperator
    {
        ExecutesAction = 0,
        DoesNotExecuteAction = 1,
    }

    #endregion
}
